<template>
  <view>
    <view class="goods-list">
      <view v-for="(item, index) in goodsList" :key="index"><my-goods :goods="item"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'GoodsList',
  components: {},
  data() {
    return {
      queryObj: {
        quuery: '', // 查询关键词
        cid: '', // 商品分类Id
        pagenum: 1,
        pagesize: 10
      },
      goodsList: [],
      total: 0,
      isLoading: false
    };
  },
  // 在浏览器中,钩子函数执行顺序: onLoad > created > mounted
  // 在小程序中,钩子函数执行顺序: created > onLoad > mounted
  // 注意: 只要在onLoad里面才接收有路由参数
  created() {},
  mounted() {},
  onLoad(options) {
    // console.log(options);
    if (options.query) this.queryObj.query = options.query;
    if (options.cid) this.queryObj.cid = options.cid;
    this.getGoodsList();
  },
  methods: {
    async getGoodsList(callback) {
      if(this.isLoading) return
      this.isLoading = true
      if(this.goodsList.length >= this.total && this.total !== 0) return
      try{
        let { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj);
        console.log(res);
        if (res.meta.status !== 200) return uni.$showMsg();
        this.goodsList = [...this.goodsList, ...res.message.goods];
        this.total = res.message.total;
        callback && callback()
      }catch(e){
        console.log(e);
      }
      this.isLoading = false
    }
  },
  // 上拉加载的事件
  onReachBottom() {
    // 让页码值自增 +1
    this.queryObj.pagenum += 1;
    // 重新获取列表数据
    this.getGoodsList();
  },
  // 下拉刷新的事件
  async onPullDownRefresh() {
    // 重置关键数据
      this.queryObj.pagenum = 1
      this.total = 0
      this.isloading = false
      this.goodsList = []
    
      // 重新发起请求
      // 关闭下拉必须在获取到数据之后
      // 方式1: 通过回调
      // this.getGoodsList(() => {uni.stopPullDownRefresh()})
      // 方式2: 通过promise
      await this.getGoodsList()
      uni.stopPullDownRefresh()
  },

};
</script>

<style lang="scss"></style>
